package com.example.quartzdemo.SpringTaskTestConfig.service;

import com.example.quartzdemo.SpringTaskTestConfig.config.CronTaskRegistrar;
import com.example.quartzdemo.SpringTaskTestConfig.config.SchedulingRunnable;
import com.example.quartzdemo.SpringTaskTestConfig.config.SysJobStatus;
import com.example.quartzdemo.SpringTaskTestConfig.mapper.SysJobPOMapper;
import com.example.quartzdemo.SpringTaskTestConfig.pojo.SysJobPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @TODO
 * @ClassName AddTime
 * @Author 81373
 * @Date 2022/11/9 17:23
 */
@Service
@Slf4j
public class SysJobRunner  implements CommandLineRunner {

    @Autowired
    static
    SysJobPOMapper sysJobPOMapper;

    @Autowired
    private static CronTaskRegistrar cronTaskRegistrar;

    @Override
    public void run(String... args) {
        // 初始加载数据库里状态为正常的定时任务
       /* QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("jobStatus", 1);
        Long aLong = sysJobPOMapper.selectCount(queryWrapper);
        log.info("查询结果 = " + aLong);
        List<SysJobPO> jobList = sysJobPOMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(jobList)) {
            for (SysJobPO job : jobList) {
                SchedulingRunnable task = new SchedulingRunnable(job.getBeanName(), job.getMethodName(), job.getMethodParams());
                cronTaskRegistrar.addCronTask(task, job.getCronExpression());
            }
            log.info("定时任务已加载完毕...");
        }*/
        log.info("定时任务已加载完毕");
    }

    /**
      * @TODO   新增定时任务
      * @Author 江
      * @Date 2022/11/9 23:51
      */
    public static String addScheduled(SysJobPO sysJobPO){
      /*  sysJobPO.setCreateTime(new Date());
        sysJobPO.setUpdateTime(new Date());
        int success = sysJobPOMapper.insert(sysJobPO);
        if (success != 1)
            return "新增失败";*/
//        else {
        System.out.println("sysJobPO = " + sysJobPO);
            if (sysJobPO.getJobStatus() == 1) {
                SchedulingRunnable task = new SchedulingRunnable(sysJobPO.getBeanName(), sysJobPO.getMethodName(),
                                                                sysJobPO.getMethodParams());
                cronTaskRegistrar.addCronTask(task, sysJobPO.getCronExpression());
            }
//        }
        return "OK";

    }

    /**
      * @TODO   修改定时任务，先移除原来的任务，再启动新任务
      * @Author 江
      * @Date 2022/11/9 23:51
      */
    @Transactional(rollbackFor = {Exception.class})
    public void editSysJob(SysJobPO sysJob) {

        SysJobPO sysJobPO = new SysJobPO();
        BeanUtils.copyProperties(sysJob, sysJobPO);
        sysJobPO.setUpdateTime(new Date());

        SysJobPO existedSysJob = sysJobPOMapper.selectById(sysJob.getJobId());
        //先移除
        SchedulingRunnable task = new SchedulingRunnable(existedSysJob.getBeanName(), existedSysJob.getMethodName(),
                                                        existedSysJob.getMethodParams());
        cronTaskRegistrar.removeCronTask(task);

        sysJobPO.setCreateTime(existedSysJob.getCreateTime());
        try {
            sysJobPOMapper.insert(sysJobPO);
            //然后判断是否开启
            if (sysJob.getJobStatus().equals(SysJobStatus.NORMAL.ordinal())) {
                SchedulingRunnable task2 = new SchedulingRunnable(sysJob.getBeanName(), sysJob.getMethodName(),
                                                            sysJob.getMethodParams());
                cronTaskRegistrar.addCronTask(task2, sysJob.getCronExpression());
            }
        } catch (Exception e) {
            log.info("-----编辑定时任务失败!", e);
//            throw new CronException("编辑定时任务失败!");
        }
    }

    /**
      * @TODO   删除定时任务
      * @Author 江
      * @Date 2022/11/9 23:51
      */
    @Transactional(rollbackFor = {Exception.class})
    public void deleteSysJobById(Integer jobId) {
        SysJobPO existedSysJob = sysJobPOMapper.selectById(jobId);
        try {
            sysJobPOMapper.deleteById(jobId);
        } catch (Exception e) {
            log.info("-----删除定时任务失败!", e);
//            throw new CronException("删除定时任务失败!");
        }
        SchedulingRunnable task = new SchedulingRunnable(existedSysJob.getBeanName(), existedSysJob.getMethodName(),
                                                        existedSysJob.getMethodParams());
        cronTaskRegistrar.removeCronTask(task);
    }

    /**
      * @TODO   定时任务启动/停止状态切换
      * @Author 江
      * @Date 2022/11/9 23:51
      */
    @Transactional(rollbackFor = {Exception.class})
    public void startOrStopSysJob(Integer jobId, Integer status) {
        SysJobPO existedSysJob = sysJobPOMapper.selectById(jobId);
        SchedulingRunnable task2 = new SchedulingRunnable(existedSysJob.getBeanName(), existedSysJob.getMethodName(), existedSysJob.getMethodParams());
        cronTaskRegistrar.removeCronTask(task2);

        existedSysJob.setJobStatus(status);
        sysJobPOMapper.insert(existedSysJob);

        if (existedSysJob.getJobStatus().equals(SysJobStatus.NORMAL.ordinal())) {
            SchedulingRunnable task = new SchedulingRunnable(existedSysJob.getBeanName(), existedSysJob.getMethodName(), existedSysJob.getMethodParams());
            cronTaskRegistrar.addCronTask(task, existedSysJob.getCronExpression());
        }
    }
}
